<!--
 * @Author: byron
 * @Date: 2021-12-08 12:01:54
 * @LastEditTime: 2022-02-18 17:15:04
-->
<template>
    <div>
        <page-header title="角色列表">
            <a-button
                type="primary"
                :size="size"
                style="margin-right: 5px"
                @click="showAddModal()"
                >新增角色</a-button
            >
        </page-header>
        <page-layout>
            <a-table :columns="columns" :data-source="roleData">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'avatar'">
                        <a-avatar :src="record.avatar" />
                    </template>
                    <template v-if="column.key === 'status'">
                        <a-switch
                            v-model:checked="record.status"
                            checked-children="启用"
                            un-checked-children="禁用"
                            @click="updateStatus(record)"
                        />
                    </template>
                    <template v-else-if="column.key === 'action'">
                        <span>
                            <a-button
                                type="primary"
                                :size="size"
                                style="margin-right: 5px"
                                @click="showEditModal(record)"
                            >
                                <template #icon>
                                    <edit-outlined />
                                </template>
                                编辑</a-button
                            >

                            <a-popconfirm
                                title="确认删除此角色？"
                                ok-text="确认"
                                cancel-text="取消"
                                @confirm="delRoleBtn(record.id)"
                            >
                                <a-button danger :size="size">
                                    <template #icon>
                                        <delete-outlined /> </template
                                    >删除</a-button
                                >
                            </a-popconfirm>
                            <a-button
                                :size="size"
                                style="margin-left: 5px"
                                type="primary"
                                danger
                                @click="showAllot(record.id)"
                            >
                                <template #icon> <setting-outlined /> </template
                                >分配权限</a-button
                            >
                        </span>
                    </template>
                </template>
            </a-table>
            <!-- 新增角色 -->
            <a-modal
                v-model:visible="addVisible"
                title="新增角色"
                @ok="addRoleBtn"
                @cancel="closeModal"
            >
                <a-form
                    ref="addFormRef"
                    :model="formState"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-item ref="name" label="角色名称" name="name">
                        <a-input v-model:value="formState.name" />
                    </a-form-item>
                    <a-form-item label="角色备注" name="remark">
                        <a-input v-model:value="formState.remark" />
                    </a-form-item>
                    <a-form-item label="角色状态" name="status">
                        <a-switch v-model:checked="formState.status" />
                    </a-form-item>
                </a-form>
            </a-modal>
            <!-- 编辑角色 -->
            <a-modal
                v-model:visible="editVisible"
                title="编辑角色"
                @ok="editRoleBtn"
                @cancel="closeEditModal"
            >
                <a-form
                    ref="editFormRef"
                    :model="editForm"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                >
                    <a-form-item label="角色id">
                        <a-input v-model:value="editForm.id" disabled />
                    </a-form-item>
                    <a-form-item ref="name" label="角色名称" name="name">
                        <a-input v-model:value="editForm.name" />
                    </a-form-item>
                    <a-form-item label="角色备注" name="remark">
                        <a-input v-model:value="editForm.remark" />
                    </a-form-item>
                    <a-form-item label="角色状态" name="status">
                        <a-switch v-model:checked="editForm.status" />
                    </a-form-item>
                </a-form>
            </a-modal>
            <!-- 分配权限 -->
            <a-drawer
                title="分配权限"
                :width="450"
                :visible="allotVisible"
                placement="left"
                :body-style="{ paddingBottom: '80px' }"
                :footer-style="{ textAlign: 'right' }"
                @close="onClose"
            >
                <a-tree
                    v-model:expandedKeys="expandedKeys"
                    v-model:checkedKeys="checkedKeys"
                    v-model:selectedKeys="selectedKeys"
                    checkable
                    autoExpandParent
                    :tree-data="treeData"
                    :field-names="fieldNames"
                >
                </a-tree>

                <template #extra>
                    <a-button style="margin-right: 8px" @click="onClose"
                        >取消</a-button
                    >
                    <a-button type="primary" @click="allotPermissionBtn"
                        >确定</a-button
                    >
                </template>
            </a-drawer>
        </page-layout>
    </div>
</template>
<script>
import {
    getRoleList,
    delRole,
    updateRole,
    getPermissionTree,
    addRole,
    editRole,
    permissionDetail,
    allotPermission,
} from '@/api/index.js'
import { message } from 'ant-design-vue'
import { computed, ref, watch, toRaw, reactive } from 'vue'
const size = 'default'
const columns = [
    {
        title: '角色Id',
        width: 100,
        dataIndex: 'id',
        key: 'id',
    },
    {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
    },
    {
        title: '角色描述',
        dataIndex: 'remark',
        key: 'remark',
    },
    {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
    },
    {
        title: '操作',
        width: 400,
        key: 'action',
    },
]
export default {
    components: {},

    setup() {
        const roleData = ref([])
        const getData = async () => {
            const { data: res } = await getRoleList({
                currentPage: 1,
                pageSize: 100,
            })
            roleData.value = res.data.list.map((e) => {
                if (e.status) {
                    e.status = true
                } else {
                    e.status = false
                }
                return e
            })
            console.log(res.data.list)
        }
        getData()

        /**
         * 删除某个角色
         */
        const delRoleBtn = async (id) => {
            const { data: res } = await delRole(id)
            const { code, msg } = res
            if (code == 200) {
                message.success('删除成功')
                getData()
                return
            }
            message.error(msg)
        }

        /**
         * 更改角色状态
         */
        const updateStatus = async (record) => {
            const { id, status } = record
            const { data: res } = await updateRole({
                id,
                status: status ? 1 : 0,
            })
            if (res.code == 200) {
                message.success('更新角色状态成功')
                return
            }
            message.error(res.msg)
        }
        /**
         * 分配权限
         */
        const fieldNames = {
            title: 'name',
            key: 'id',
        }
        let RoleId = 0
        const treeData = ref([])
        const allotVisible = ref(false)
        const showAllot = async (id) => {
            RoleId = id
            const { data: res } = await permissionDetail(id)
            console.log('@@@@', res)
            checkedKeys.value = res.data.map((e) => {
                return e.pid
            })
            allotVisible.value = true
            getPermission((res) => {
                treeData.value = res.data
            })
        }
        const onClose = () => {
            allotVisible.value = false
        }
        const getPermission = async (fn) => {
            const { data: res } = await getPermissionTree()
            fn(res)
        }
        const allotPermissionBtn = async () => {
            console.log('@@@', checkedKeys.value)
            const { data: res } = await allotPermission({
                id: RoleId,
                permissionIdList: checkedKeys.value,
            })
            allotVisible.value = false

            if (res.code == 200) {
                message.success('分配权限成功')
                return
            }
            message.error(res.msg)
        }
        const expandedKeys = ref([101, 102, 103, 147])
        const selectedKeys = ref([])
        const checkedKeys = ref([])
        watch(expandedKeys, () => {
            console.log('expandedKeys', expandedKeys)
        })
        watch(selectedKeys, () => {
            console.log('selectedKeys', selectedKeys)
        })
        watch(checkedKeys, () => {
            console.log('checkedKeys', checkedKeys)
        })
        /**
         * 新增角色
         *
         */
        const addVisible = ref(false)
        const showAddModal = () => {
            addVisible.value = true
        }

        const addFormRef = ref()
        const formState = reactive({
            id: 0,
            name: '',
            remark: '',
            status: false,
        })
        const rules = {
            name: [
                {
                    required: true,
                    message: '请输入角色名称',
                    trigger: 'blur',
                },
                {
                    min: 2,
                    max: 6,
                    message: '长度为2到6个字符',
                    trigger: 'blur',
                },
            ],
            remark: [
                {
                    required: true,
                    message: '请输入角色备注',
                    trigger: 'blur',
                },
            ],
        }
        const status = computed(() => (formState.status ? 1 : 0))
        const addRoleBtn = async () => {
            const { data: res } = await addRole(
                Object.defineProperty(toRaw(formState), 'status', {
                    value: status.value,
                    writable: true,
                    enumerable: true,
                    configurable: true,
                })
            )
            if (res.code == 200) {
                message.success('新增角色成功')
                getData()
                addVisible.value = false
                addFormRef.value.resetFields()
                return
            }
            addFormRef.value.resetFields()
            message.error(res.msg)
        }
        const closeModal = () => {
            addFormRef.value.resetFields()
        }

        /**
         * 编辑角色
         *
         */
        const editForm = reactive({
            id: 0,
            name: '',
            remark: '',
            status: false,
        })
        const editVisible = ref(false)
        const editRoleBtn = () => {
            editFormRef.value
                .validate()
                .then(async () => {
                    console.log('@@@', formState)
                    console.log('@@@', status.value)
                    const { data: res } = await editRole(
                        Object.defineProperty(toRaw(editForm), 'status', {
                            value: status.value,
                            writable: true,
                            enumerable: true,
                            configurable: true,
                        })
                    )
                    if (res.code == 200) {
                        editVisible.value = false
                        editFormRef.value.resetFields()
                        getData()
                        message.success('编辑角色成功')
                        return
                    }
                    editFormRef.value.resetFields()
                    message.error(res.msg)
                })
                .catch((error) => {
                    console.log(error)
                    message.error('请正确填写表单项')
                })
        }
        const closeEditModal = () => {
            editFormRef.value.resetFields()
        }
        const showEditModal = (record) => {
            const { id, name, remark, status } = record
            editForm.id = id
            editForm.name = name
            editForm.remark = remark
            editForm.status = status
            editVisible.value = true
        }
        const editFormRef = ref()
        return {
            updateStatus,
            columns,
            roleData,
            delRoleBtn,
            size,
            allotVisible,
            allotPermissionBtn,
            showAllot,
            onClose,
            treeData,
            fieldNames,
            expandedKeys,
            addVisible,
            showAddModal,
            rules,
            addFormRef,
            formState,
            editForm,
            addRoleBtn,
            closeModal,
            labelCol: {
                span: 4,
            },
            wrapperCol: {
                span: 14,
            },
            editVisible,
            editRoleBtn,
            closeEditModal,
            editFormRef,
            showEditModal,
            selectedKeys,
            checkedKeys,
        }
    },
}
</script>
